﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace mal.WP7.FreeRemote.WebSite
{
    /// <summary>
    /// Summary description for Freemote
    /// </summary>
    public class FreeRemoteControl : IHttpHandler
    {
        private static List<FreeRemoteCommand> commands;

        public void ProcessRequest(HttpContext context)
        {
            if (commands == null)
            {
                commands = new List<FreeRemoteCommand>();
            }

            string key = context.Request["key"];
            string ip = context.Request.ServerVariables["REMOTE_ADDR"];
            string action = context.Request["action"];

            if (action == "get")
            {
                context.Response.ContentType = "application/json";
                string json = this.GetJson();
                context.Response.Write(json);
            }
            else
            {
                FreeRemoteCommand command = new FreeRemoteCommand();
                command.Date = DateTime.Now;
                command.Ip = ip;
                command.Key = key;

                commands.Add(command);
            }
        }

        private string GetJson()
        {
            StringBuilder json = new StringBuilder();

            json.Append("{\"commands\":[");

            for (int i = 0; i < commands.Count; i++)
            {
                try
                {
                    FreeRemoteCommand command = commands[i];
                    json.AppendFormat("{{\"key\":\"{0}\"", command.Key);
                    json.AppendFormat(",\"ip\":\"{0}\"", command.Ip);
                    json.AppendFormat(",\"date\":\"{0}\"}}", command.Date);

                    if (i < commands.Count - 1)
                    {
                        json.Append(",");
                    }
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }

            json.Append("]}");

            commands = null;
            return json.ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}